package de.wbh.gwt.form.layouter.shared.activity;

import java.util.ArrayList;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.inject.client.AsyncProvider;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

import de.wbh.gwt.form.layouter.shared.place.CreateConfigurationPlace;
import de.wbh.gwt.form.layouter.shared.rpc.AvailableFileService;
import de.wbh.gwt.form.layouter.shared.rpc.AvailableFileServiceAsync;

public class LoadPdfActivity extends AbstractActivity implements LoadPdfView.Presenter {

	private static final String DOWNLOAD_ACTION_URL = GWT.getModuleBaseURL() + "download";

	private final AvailableFileServiceAsync filesService = GWT.create(AvailableFileService.class);

	private final AsyncProvider<LoadPdfView> viewProvider;
	private final PlaceController placeController;

	private LoadPdfView view;

	@Inject
	public LoadPdfActivity(AsyncProvider<LoadPdfView> viewProvider, PlaceController placeController) {
		this.viewProvider = viewProvider;
		this.placeController = placeController;
	}

	private String getOnlyNameOfFile(final String finalFilename) {
		String filname;
		int pos = finalFilename.lastIndexOf(".");
		if (pos == -1) {
			filname = finalFilename;
		} else {
			filname = finalFilename.substring(0, pos);
		}
		return filname;
	}

	@Override
	public boolean loadFromServer(String name) {
		next(name);
		return true;
	}

	@Override
	public boolean loadFromUrl(String url) {
		if (url.endsWith("pdf") || url.endsWith("PDF")) {
			String filename = "";
			int pos = url.lastIndexOf("/");
			if (pos == -1) {
				filename = url;
			}
			filename = url.substring(pos + 1);
			RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, DOWNLOAD_ACTION_URL + "?filename=" + filename + "&url=" + url);
			final String finalFilename = filename;
			try {
				builder.sendRequest("", new RequestCallback() {
					@Override
					public void onError(Request request, Throwable exception) {
						exception.printStackTrace();
					}

					@Override
					public void onResponseReceived(Request request, Response response) {
						if (response.getStatusCode() == HttpServletResponse.SC_CONFLICT) {
							Window.alert("Die Datei ist schon auf dem Server vorhanden.");
						} else if (response.getStatusCode() == HttpServletResponse.SC_OK) {
							String filname = getOnlyNameOfFile(finalFilename);
							next(filname);
						}

					}

				});
			} catch (RequestException e) {
				e.printStackTrace();
			}

		} else {
			Window.alert("Bitte geben Sie eine Url ein, unter der eine pdf-Datei verfügbar ist.");
		}
		return false;
	}

	@Override
	public boolean loadLocal(String fileName) {
		next(getOnlyNameOfFile(fileName));
		return false;
	}

	private void next(String pdfName) {
		if (this.placeController.getWhere() instanceof CreateConfigurationPlace) {
			CreateConfigurationPlace place = ((CreateConfigurationPlace) this.placeController.getWhere()).next();
			place.setPdfName(pdfName);
			this.placeController.goTo(place);
		}
	}

	@Override
	public void start(final AcceptsOneWidget panel, EventBus eventBus) {
		this.viewProvider.get(new AsyncCallback<LoadPdfView>() {

			@Override
			public void onFailure(Throwable caught) {
				caught.printStackTrace();
			}

			@Override
			public void onSuccess(LoadPdfView result) {
				LoadPdfActivity.this.view = result;
				LoadPdfActivity.this.view.setPresenter(LoadPdfActivity.this);
				LoadPdfActivity.this.filesService.getAvailablePdfFiles(new AsyncCallback<ArrayList<String>>() {

					@Override
					public void onFailure(Throwable caught) {
						caught.printStackTrace();
					}

					@Override
					public void onSuccess(ArrayList<String> result) {
						LoadPdfActivity.this.view.getServerList().setRowData(result);

					}
				});

				panel.setWidget(LoadPdfActivity.this.view);
			}
		});

	}

}
